package com.kkd.kkdapp.db.base;

import java.lang.reflect.Field;

import com.kkd.kkdapp.db.annotate.EADBField;
import com.kkd.kkdapp.db.annotate.EADBField.EADBFieldMode;
import com.kkd.kkdapp.utils.LogUtil;

import android.database.Cursor;



/**
 * This class is base model for db object.
 * 
 * @date 2014-12-1
 * @author askzhao
 * 
 */
public class EABaseModel {
	private static final String TAG = EABaseModel.class.getSimpleName();
	public static final int CONTAINED = -2016;//表明已经存在该消息

	/** 主键 */
	public static final String _ID = "_id";

	@EADBField(fieldName = _ID, mode = EADBFieldMode.Key)
	public long rowid;

	/**
	 * 创建Table
	 * 
	 * @param clazz
	 * @return
	 */
	public static String createTableSql(Class<?> clazz) {
		return SqlBuilder.getCreateTableSql(clazz);
	}

	/**
	 * 放弃Table
	 * 
	 * @param clazz
	 * @return
	 */
	public String dropTableSql() {
		return SqlBuilder.getDropTableSql(getClass());
	}

	public static void closeCursor(Cursor cursor) {

		if (cursor != null && !cursor.isClosed()) {
			try {
				cursor.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 解析成java对象
	 * 
	 * @param clazz
	 * @param c
	 * @param fs
	 * @return
	 */
	public static <T> T parseToEntity(Class<T> clazz, Cursor c, Field[] fs) {
		T t = null;
		try {
			t = clazz.newInstance();
			for (int columnIndex = 0, count = c.getColumnCount(); columnIndex < count; columnIndex++) {
				String columnName = c.getColumnName(columnIndex);
				for (int i = 0; i < fs.length; i++) {
					if ("_id".equals(columnName)
							&& "rowid".equals(fs[i].getName())) { // 处理主键
						fs[i].set(t, EATool.getValue(c, fs[i], columnName));
						break;
					} else if (columnName.equals(fs[i].getName())) {
						fs[i].set(t, EATool.getValue(c, fs[i], columnName));
						break;
					}
				}
			}
		} catch (Exception e) {
			LogUtil.exception(e);
		}
		return t;
	}
}
